<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>13. Interactive Input Editing and History Substitution &mdash; Python v2.7 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.7',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.7 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.7 documentation" href="../index.html" />
    <link rel="up" title="The Python Tutorial" href="index.html" />
    <link rel="next" title="14. Floating Point Arithmetic: Issues and Limitations 浮点数算法：争议和限制" href="floatingpoint.html" />
    <link rel="prev" title="12. What Now? 接下来？" href="whatnow.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="floatingpoint.html" title="14. Floating Point Arithmetic: Issues and Limitations 浮点数算法：争议和限制"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="whatnow.html" title="12. What Now? 接下来？"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.7 documentation</a> &raquo;</li>

          <li><a href="index.html" accesskey="U">The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="interactive-input-editing-and-history-substitution">
<span id="tut-interacting"></span><h1>13. Interactive Input Editing and History Substitution<a class="headerlink" href="#interactive-input-editing-and-history-substitution" title="Permalink to this headline">¶</a></h1>
<p>Some versions of the Python interpreter support editing of the current input
line and history substitution, similar to facilities found in the Korn shell and
the GNU Bash shell.  This is implemented using the <a class="reference external" href="http://tiswww.case.edu/php/chet/readline/rltop.html">GNU Readline</a> library,
which supports Emacs-style and vi-style editing.  This library has its own
documentation which I won&#8217;t duplicate here; however, the basics are easily
explained.  The interactive editing and history described here are optionally
available in the Unix and Cygwin versions of the interpreter.</p>
<p>有些版本的 Python 解释器支持输入行编辑和历史回溯，类似 Korn shell 和
GNU bash shell 的功能。这是通过 <a class="reference external" href="http://tiswww.case.edu/php/chet/readline/rltop.html">GNU Readline</a> 库实现的。它支持 Emacs
风格和 vi 风格的编辑。这个库有它自己的文档，在此不重复了。不过，基本的
东西很容易演示。交互式编辑和历史查阅在 Unix 和 Cygwin 版中是可选项。</p>
<p>This chapter does <em>not</em> document the editing facilities of Mark Hammond&#8217;s
PythonWin package or the Tk-based environment, IDLE, distributed with Python.
The command line history recall which operates within DOS boxes on NT and some
other DOS and Windows flavors  is yet another beast.</p>
<p>本章 <em>不是</em> 马克 哈密尔顿的 PythonWin 包和随 Python 发布的基于 TK 的
IDLE 环境的文档。 NT 系统和其它 DOS、Windows 系统上的 DOS 窗中的命令行
历史回调，属于另一个话题。</p>
<div class="section" id="line-editing">
<span id="tut-lineediting"></span><h2>13.1. Line Editing 行编辑<a class="headerlink" href="#line-editing" title="Permalink to this headline">¶</a></h2>
<p>If supported, input line editing is active whenever the interpreter prints a
primary or secondary prompt.  The current line can be edited using the
conventional Emacs control characters.  The most important of these are:
<tt class="docutils literal"><span class="pre">C-A</span></tt> (Control-A) moves the cursor to the beginning of the line, <tt class="docutils literal"><span class="pre">C-E</span></tt>
to the end, <tt class="docutils literal"><span class="pre">C-B</span></tt> moves it one position to the left, <tt class="docutils literal"><span class="pre">C-F</span></tt> to the
right.  Backspace erases the character to the left of the cursor, <tt class="docutils literal"><span class="pre">C-D</span></tt> the
character to its right. <tt class="docutils literal"><span class="pre">C-K</span></tt> kills (erases) the rest of the line to the
right of the cursor, <tt class="docutils literal"><span class="pre">C-Y</span></tt> yanks back the last killed string.
<tt class="docutils literal"><span class="pre">C-underscore</span></tt> undoes the last change you made; it can be repeated for
cumulative effect.</p>
<p>如果支持，无论解释器打印主提示符或从属提示符，行编辑都会激活。当前行可
以用 Emacs 风格的快捷键编辑。其中最重要的是： <tt class="docutils literal"><span class="pre">C-A</span></tt> （Control-A）
将光标移动到行首，　:kbd:<cite>C-E</cite> 移动到行尾， <tt class="docutils literal"><span class="pre">C-B</span></tt> 向左移一个字
符， <tt class="docutils literal"><span class="pre">C-F</span></tt> 向右移一位。退格向左删除一个符串， <tt class="docutils literal"><span class="pre">C-D</span></tt> 向右删除
一个字符。 <tt class="docutils literal"><span class="pre">C-K</span></tt> 删掉光标右边直到行尾的所有字符， <tt class="docutils literal"><span class="pre">C-Y</span></tt> 将最
后一次删除的字符串粘贴到光标位置。 <tt class="docutils literal"><span class="pre">C-underscore</span></tt> （underscores
即下划线，译注）撤销最后一次修改，它可以因积累作用重复。</p>
</div>
<div class="section" id="history-substitution">
<span id="tut-history"></span><h2>13.2. History Substitution 历史回溯<a class="headerlink" href="#history-substitution" title="Permalink to this headline">¶</a></h2>
<p>History substitution works as follows.  All non-empty input lines issued are
saved in a history buffer, and when a new prompt is given you are positioned on
a new line at the bottom of this buffer. <tt class="docutils literal"><span class="pre">C-P</span></tt> moves one line up (back) in
the history buffer, <tt class="docutils literal"><span class="pre">C-N</span></tt> moves one down.  Any line in the history buffer
can be edited; an asterisk appears in front of the prompt to mark a line as
modified.  Pressing the <tt class="docutils literal"><span class="pre">Return</span></tt> key passes the current line to the
interpreter.  <tt class="docutils literal"><span class="pre">C-R</span></tt> starts an incremental reverse search; <tt class="docutils literal"><span class="pre">C-S</span></tt> starts
a forward search.</p>
<p>历史代替可以工作。所有非空的输入行都被保存在历史缓存中，获得一个新的提
示符的时候，你处于这个缓存的最底的空行。 <tt class="docutils literal"><span class="pre">C-P</span></tt> 在历史缓存中上溯一
行， <tt class="docutils literal"><span class="pre">C-N</span></tt> 向下移一行。历史缓存中的任一行都可以编辑；按下
　:kbd:<cite>Return</cite> 键时将当前行传入解释器。 <tt class="docutils literal"><span class="pre">C-R</span></tt> 开始一个增量向前搜
索；:kbd:<cite>C-S</cite> 开始一个向后搜索。</p>
</div>
<div class="section" id="key-bindings">
<span id="tut-keybindings"></span><h2>13.3. Key Bindings 快捷键绑定<a class="headerlink" href="#key-bindings" title="Permalink to this headline">¶</a></h2>
<p>The key bindings and some other parameters of the Readline library can be
customized by placing commands in an initialization file called
<tt class="docutils literal"><span class="pre">~/.inputrc</span></tt>.  Key bindings have the form :</p>
<p>Readline 库的快捷键绑定和其它一些参数可以通过名为 <tt class="docutils literal"><span class="pre">~/.inputrc</span></tt>
的初始化文件的替换命名来定制。快捷键绑定如下形式</p>
<div class="highlight-python"><pre>key-name: function-name</pre>
</div>
<p>or :</p>
<p>或</p>
<div class="highlight-python"><pre>"string": function-name</pre>
</div>
<p>and options can be set with :</p>
<p>选项可以如下设置</p>
<div class="highlight-python"><pre>set option-name value</pre>
</div>
<p>For example:</p>
<p>例如</p>
<div class="highlight-python"><pre># I prefer vi-style editing:
set editing-mode vi

# Edit using a single line:
set horizontal-scroll-mode On

# Rebind some keys:
Meta-h: backward-kill-word
"\C-u": universal-argument
"\C-x\C-r": re-read-init-file</pre>
</div>
<p>Note that the default binding for <tt class="docutils literal"><span class="pre">Tab</span></tt> in Python is to insert a <tt class="docutils literal"><span class="pre">Tab</span></tt>
character instead of Readline&#8217;s default filename completion function.  If you
insist, you can override this by putting :</p>
<p>需要注意的是 Python 中默认 <tt class="docutils literal"><span class="pre">Tab</span></tt> 绑定为插入一个 <tt class="docutils literal"><span class="pre">Tab</span></tt> 字符
而不是 Readline 库的默认文件名完成函数，如果你想用这个，可以将以下内容
插入</p>
<div class="highlight-python"><pre>Tab: complete</pre>
</div>
<p>in your <tt class="docutils literal"><span class="pre">~/.inputrc</span></tt>.  (Of course, this makes it harder to type indented
continuation lines if you&#8217;re accustomed to using <tt class="docutils literal"><span class="pre">Tab</span></tt> for that purpose.)</p>
<p>到你的 <tt class="docutils literal"><span class="pre">~/.inputrc</span></tt> 中来覆盖它。（当然，如果你真的把 <tt class="docutils literal"><span class="pre">Tab</span></tt>
设置成这样，就很难在后继行中插入缩进。）</p>
<p id="index-1826">Automatic completion of variable and module names is optionally available.  To
enable it in the interpreter&#8217;s interactive mode, add the following to your
startup file: <a class="footnote-reference" href="#id5" id="id1">[1]</a>  :</p>
<p>自动完成变量和模块名也可以激活生效。要使之在解释器交互模式中可用，在你
的启动文件中加入下面内容: <a class="footnote-reference" href="#id6" id="id2">[2]</a></p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">rlcompleter</span><span class="o">,</span> <span class="nn">readline</span>
<span class="n">readline</span><span class="o">.</span><span class="n">parse_and_bind</span><span class="p">(</span><span class="s">&#39;tab: complete&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This binds the <tt class="docutils literal"><span class="pre">Tab</span></tt> key to the completion function, so hitting the
<tt class="docutils literal"><span class="pre">Tab</span></tt> key twice suggests completions; it looks at Python statement names,
the current local variables, and the available module names.  For dotted
expressions such as <tt class="docutils literal"><span class="pre">string.a</span></tt>, it will evaluate the expression up to the
final <tt class="docutils literal"><span class="pre">'.'</span></tt> and then suggest completions from the attributes of the resulting
object.  Note that this may execute application-defined code if an object with a
<a title="object.__getattr__" class="reference external" href="../reference/datamodel.html#object.__getattr__"><tt class="xref docutils literal"><span class="pre">__getattr__()</span></tt></a> method is part of the expression.</p>
<p>这个操作将 <tt class="docutils literal"><span class="pre">Tab</span></tt> 绑定到完成函数，故按 <tt class="docutils literal"><span class="pre">Tab</span></tt> 键两次会给出建议
的完成内容；它查找　Python 命名、当前的局部变量、有效的模块名。对于类
似 <tt class="docutils literal"><span class="pre">string.a</span></tt> 这样的文件名，它会解析 <tt class="docutils literal"><span class="pre">'.'</span></tt> 相关的表达式，从返回的
结果对象中获取属性，以提供完成建议。需要注意的是，如果对象的
<a title="object.__getattr__" class="reference external" href="../reference/datamodel.html#object.__getattr__"><tt class="xref docutils literal"><span class="pre">__getattr__()</span></tt></a> 方法是此表达式的一部分，这可能会执行应用程序定
义代码。</p>
<p>A more capable startup file might look like this example.  Note that this
deletes the names it creates once they are no longer needed; this is done since
the startup file is executed in the same namespace as the interactive commands,
and removing the names avoids creating side effects in the interactive
environment.  You may find it convenient to keep some of the imported modules,
such as <a title="Miscellaneous operating system interfaces." class="reference external" href="../library/os.html#module-os"><tt class="xref docutils literal"><span class="pre">os</span></tt></a>, which turn out to be needed in most sessions with the
interpreter. :</p>
<p>更有用的初始化文件可能是下面这个例子这样的。要注意一旦创建的名字没用
了，它会删掉它们；因为初始化文件作为解释命令与之在同一个命名空间执行，
在交互环境中删除命名带来了边际效应。可能你发现了它体贴的保留了一些导入
模块，类似 <a title="Miscellaneous operating system interfaces." class="reference external" href="../library/os.html#module-os"><tt class="xref docutils literal"><span class="pre">os</span></tt></a> ，在解释器的大多数使用场合中都会用到它们。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Add auto-completion and a stored history file of commands to your Python</span>
<span class="c"># interactive interpreter. Requires Python 2.0+, readline. Autocomplete is</span>
<span class="c"># bound to the Esc key by default (you can change it - see readline docs).</span>
<span class="c">#</span>
<span class="c"># Store the file in ~/.pystartup, and set an environment variable to point</span>
<span class="c"># to it:  &quot;export PYTHONSTARTUP=/home/user/.pystartup&quot; in bash.</span>
<span class="c">#</span>
<span class="c"># Note that PYTHONSTARTUP does *not* expand &quot;~&quot;, so you have to put in the</span>
<span class="c"># full path to your home directory.</span>

<span class="kn">import</span> <span class="nn">atexit</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">readline</span>
<span class="kn">import</span> <span class="nn">rlcompleter</span>

<span class="n">historyPath</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="s">&quot;~/.pyhistory&quot;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">save_history</span><span class="p">(</span><span class="n">historyPath</span><span class="o">=</span><span class="n">historyPath</span><span class="p">):</span>
    <span class="kn">import</span> <span class="nn">readline</span>
    <span class="n">readline</span><span class="o">.</span><span class="n">write_history_file</span><span class="p">(</span><span class="n">historyPath</span><span class="p">)</span>

<span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">historyPath</span><span class="p">):</span>
    <span class="n">readline</span><span class="o">.</span><span class="n">read_history_file</span><span class="p">(</span><span class="n">historyPath</span><span class="p">)</span>

<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">save_history</span><span class="p">)</span>
<span class="k">del</span> <span class="n">os</span><span class="p">,</span> <span class="n">atexit</span><span class="p">,</span> <span class="n">readline</span><span class="p">,</span> <span class="n">rlcompleter</span><span class="p">,</span> <span class="n">save_history</span><span class="p">,</span> <span class="n">historyPath</span>
</pre></div>
</div>
</div>
<div class="section" id="alternatives-to-the-interactive-interpreter">
<span id="tut-commentary"></span><h2>13.4. Alternatives to the Interactive Interpreter 其它交互式解释器<a class="headerlink" href="#alternatives-to-the-interactive-interpreter" title="Permalink to this headline">¶</a></h2>
<p>This facility is an enormous step forward compared to earlier versions of the
interpreter; however, some wishes are left: It would be nice if the proper
indentation were suggested on continuation lines (the parser knows if an indent
token is required next).  The completion mechanism might use the interpreter&#8217;s
symbol table.  A command to check (or even suggest) matching parentheses,
quotes, etc., would also be useful.</p>
<p>跟早先版本的解释器比，现在已经有了很大的进步。不过，还是有些期待没有完
成：它应该在后继行中优美的提供缩进（解释器知道下一行是否需要缩
进）建议。完成机制可以使用解释器的符号表。命名检查（或进一步建议）匹配
括号、引号等等。</p>
<p>One alternative enhanced interactive interpreter that has been around for quite
some time is <a class="reference external" href="http://ipython.scipy.org/">IPython</a>, which features tab completion, object exploration and
advanced history management.  It can also be thoroughly customized and embedded
into other applications.  Another similar enhanced interactive environment is
<a class="reference external" href="http://www.bpython-interpreter.org/">bpython</a>.</p>
<p>另有一个强化交互式解释器已经存在一段时间了，它就是 <a href="#id3"><span class="problematic" id="id4">`</span></a>IPython`，
它支持 tab 完成，对象浏览和高级历史管理。它也可以完全定制或嵌入到其它
应用程序中。另一个类似的强化交互环境是　`bpython`。</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Python will execute the contents of a file identified by the
<span class="target" id="index-1827"></span><a class="reference external" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><strong class="xref">PYTHONSTARTUP</strong></a> environment variable when you start an interactive
interpreter.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>启动交互解释器时，Python 可以执行 <span class="target" id="index-1828"></span><a class="reference external" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><strong class="xref">PYTHONSTARTUP</strong></a> 环境变量所指
定的文件内容。</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="#">13. Interactive Input Editing and History Substitution</a><ul>
<li><a class="reference external" href="#line-editing">13.1. Line Editing 行编辑</a></li>
<li><a class="reference external" href="#history-substitution">13.2. History Substitution 历史回溯</a></li>
<li><a class="reference external" href="#key-bindings">13.3. Key Bindings 快捷键绑定</a></li>
<li><a class="reference external" href="#alternatives-to-the-interactive-interpreter">13.4. Alternatives to the Interactive Interpreter 其它交互式解释器</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="whatnow.html"
                                  title="previous chapter">12. What Now? 接下来？</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="floatingpoint.html"
                                  title="next chapter">14. Floating Point Arithmetic:  Issues and Limitations 浮点数算法：争议和限制</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
  <li><a href="../bugs.html">Report a Bug</a></li>
  <li><a href="../_sources/tutorial/interactive.txt"
         rel="nofollow">Show Source</a></li>
</ul>

          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="floatingpoint.html" title="14. Floating Point Arithmetic: Issues and Limitations 浮点数算法：争议和限制"
             >next</a> |</li>
        <li class="right" >
          <a href="whatnow.html" title="12. What Now? 接下来？"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.7 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2010, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Oct 04, 2010.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.5.
    </div>

  </body>
</html>